package com.tianheng.modbus.client;

/**************************************************
 * copyright (c) 2020, peng.cao@tianheng-uestc.com All Rights Reserved.
 * created by peng.cao
 * date:       2020/7/23 0023
 * since:      1.0.0.1
 * description:
 *
 **************************************************/
import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;

/**
 * 处理服务端返回的数据
 *
 * @author Administrator
 *
 */
public class SimpleClientHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("client channelActive..");
            ctx.writeAndFlush(Unpooled.copiedBuffer("" +
                    "开始", CharsetUtil.UTF_8)); // 必须有flush
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(msg);
        System.out.println("client channelRead..");
        ByteBuf result = (ByteBuf) msg;
        byte[] result1 = new byte[result.readableBytes()];
        result.readBytes(result1);
        String value = new String(result1,"UTF-8");
        System.out.println("服务器端返回的数据"+value);
        ctx.writeAndFlush(Unpooled.copiedBuffer(value, CharsetUtil.UTF_8));
        AttributeKey<String> key = AttributeKey.valueOf("ServerData");
        ctx.channel().attr(key).set("客户端处理完毕");
    }

}